<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>
<script>

    // T = T1 + T2 + T3
    /* var p1 = getNumAsync(1,2000); // 2s => {<fulfilled>:1}

    p1.then(function(arg){
        console.log("fulfilled",arg);
        var p2 = getNumAsync(2,1000);  // 1s => {<fulfilled>:2}
        return p2;
    }).then(function(arg){
        console.log("fulfilled",arg);
        var p3 = getNumAsync(3,3000);  // 3s => {<fulfilled>:3}
        return p3;
    }).then(function(arg){
        console.log("fulfilled",arg);
    }).catch(function(err){
        console.log("rejected",err);
    }) */



    // 同时发送请求 =>   等待2s打印1,再打印2,等待1s打印3
    var p1 = getNumAsync(1, 2000);  // 2s => {<fulfilled>:1}
    var p2 = getNumAsync(2, 1000);  // 1s => {<fulfilled>:2}
    var p3 = getNumAsync(3, 3000);  // 3s => {<fulfilled>:3}

    p1.then(function (arg) {
        console.log("fulfilled", arg);
        return p2;
    }).then(function (arg) {
        console.log("fulfilled", arg);
        return p3;
    }).then(function (arg) {
        console.log("fulfilled", arg);
    }).catch(function (err) {
        console.log("rejected", err);
    })









    function getNumAsync(num, delay = 0, isFulfilled = true) {
        var p = new Promise(function (resolve, reject) {
            // 回调函数 -> 容器 -> 用来存放异步操作 (根据异步操作的结果改变状态)
            setTimeout(() => {
                isFulfilled ? resolve(num) : reject(num); // {<fulfilled>:1}
                // console.log(p);
            }, delay);
        })
        return p;  // {<pending>:undefined}
    }
</script>

</html>